package com.xinyue.ext.reader.bean;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.Element;
import org.dom4j.Node;

import com.xinyue.ext.Label;
import com.xinyue.ext.data.FieldData;
import com.xinyue.ext.exception.ManyException;
import com.xinyue.ext.reader.ParamHolder;
import com.xinyue.ext.util.StringUtil;

public class JoinReader implements Label{
	private static ParamHolder holder;
	
	//私有构造器
	private JoinReader() {
	}
	//私有内部类
	private static class SingletonHolder{
        private static JoinReader instance = new JoinReader();  
    }
	/***
	 * 获得实例对象
	 */
	public static JoinReader getInstance(ParamHolder holder) {
		JoinReader.holder = holder;
		return SingletonHolder.instance;
	}
	
	
	/**
	 * 读取join标签数据
	 * @param many
	 * @throws ManyException
	 */
	@SuppressWarnings("unchecked")
	public void joinRead(Element many) throws ManyException{
		List<Element> joins = many.elements(join_);
		
		if(joins == null || joins.size() != 2) {
			throw new ManyException("必须定义join标签且只能定义2个。", holder.getException());
		}
		
		List<FieldData> fields = new ArrayList<FieldData>();
		for (Element join: joins) {
			//属性
			FieldData field = new FieldData();
			
			String entity = join.attributeValue(entity_);
			String key = join.attributeValue(join_key_);
			
			//空数据验证
			if(StringUtil.isNull(entity)) {
				throw new ManyException("join标签entity属性未定义或其值为空。", holder.getException());
			}
			if(StringUtil.isNull(key)) {
				throw new ManyException("join标签join-key属性未定义或其值为空。", holder.getException());
			}
			
			//数据合法性验证
			Node n = many.selectSingleNode("/build-mapping/entity[@name='" + entity + "']");
			if(n == null) {
				throw new ManyException("join标签entity属性值非法：" + entity, holder.getException());
			}else {
				Node nk = many.selectSingleNode("/build-mapping/entity[@name='" + entity + "']/id[@name='" + key + "']");
				if(nk == null) {
					nk = many.selectSingleNode("/build-mapping/entity[@name='" + entity + "']/property[@name='" + key + "']");
				}
				
				if(nk == null) {
					throw new ManyException("join标签join-key属性值非法：" + key, holder.getException());
				}else {
					//验证通过则setter数据
					field.setType(nk.valueOf("@type"));
					//java属性名和数据库字段名对应
					String t_name = nk.valueOf("@t_name");
					if(!StringUtil.isNull(t_name)) {
						field.setDbName(t_name);
						field.setAnn_column("@Column(name=\"" + t_name + "\")");
						holder.getBeanImpt().add("javax.persistence.Column");
					}
					field.setName(key);
					field.setNullable(false);
				}
			}
			
			fields.add(field);
		}
		
		holder.getEntity().setJoins(fields);
	}
}
